//
//  PKPublishShortVideoController.swift
//  Panku
//
//  Created by mac on 2017/2/15.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import HTHorizontalSelectionList
import SVProgressHUD

class PKPublishShortVideoController: PKBaseViewController {
    
    //MARK: - properties
    //viewModel
    var viewModel:PKPublishShortVideoViewModel?
    //UI
    lazy var selectionList = HTHorizontalSelectionList()
    lazy var secondsPicker = UIPickerView()
    
    lazy var previewView = PKBaseView()
    lazy var recordButton = PKBaseButton.createButton()
    lazy var deleteButton = PKBaseButton.createButton()
    lazy var editButton = PKBaseButton.createButton()
    lazy var toggleButton = PKBaseButton.createButton()
    lazy var dismissButton = PKBaseButton.createButton()
    lazy var progressBarView = UIProgressView(progressViewStyle: .bar)
    lazy var bottomContainerView = PKBaseView()
    lazy var cameraUtils = PKCameraUtils.sharedInstance
    
    //MARK: - int
    init(viewModel:PKPublishShortVideoViewModel){
        self.viewModel = viewModel
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - life circle
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //打开预览界面
        self.cameraUtils.startCapture()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //关闭预览界面
        self.cameraUtils.stopCapture()
    }

    //MARK: - UI
    override func setupRootView() {
        view.backgroundColor = UIColor.black
    }
    
    override func setupSubViews() {
        view.addSubview(previewView)
        view.addSubview(bottomContainerView)
        bottomContainerView.addSubview(recordButton)
        bottomContainerView.addSubview(deleteButton)
        view.addSubview(editButton)
        view.addSubview(toggleButton)
        view.addSubview(dismissButton)
        view.addSubview(progressBarView)
        
        view.addSubview(selectionList)
        view.addSubview(secondsPicker)
        
        previewView.addSubview(cameraUtils.previewView!)
        
        previewView.backgroundColor = UIColor.darkGray
        let leftSwipeGesture = UISwipeGestureRecognizer { (gesture) in
            //滤镜序号减1
            if (self.selectionList.selectedButtonIndex != 0){
                
                let index = self.selectionList.selectedButtonIndex-1
                self.selectionList.setSelectedButtonIndex(index, animated: true)
                //切换滤镜
                let title = self.viewModel?.titleForItemWith(index: index)
                self.cameraUtils.setFilter(filter: self.viewModel!.filterWith(title: title!))
            }
        }
        
        leftSwipeGesture.direction = .left
        
        let rightSwipeGesture = UISwipeGestureRecognizer { (gesture) in
            //滤镜序号加1
            if (self.selectionList.selectedButtonIndex < self.viewModel!.numberOfItemsForSelectionList()-1){
                let index = self.selectionList.selectedButtonIndex+1
                self.selectionList.setSelectedButtonIndex(index, animated: true)
                
                //切换滤镜
                let title = self.viewModel?.titleForItemWith(index: index)
                self.cameraUtils.setFilter(filter: self.viewModel!.filterWith(title: title!))
            }
        }
        rightSwipeGesture.direction = .right
        
        previewView.addGestureRecognizer(leftSwipeGesture)
        previewView.addGestureRecognizer(rightSwipeGesture)
        
        progressBarView.progress = 0.3
        progressBarView.progressTintColor = UIColor.blue
        
        dismissButton.setImage(R.image.publish_shortVideo_dismiss(), for: .normal)
        dismissButton.addBlock(for: .touchUpInside) { (_) in
            //dismiss
            self.dismiss(animated: false, completion: { 
                //finish callback
            })
        }
        
        recordButton.addBlock(for: .touchUpInside) { (button) in
            
            if self.cameraUtils.isRecording == false{
                self.recordButton.isSelected = true
                self.cameraUtils.startRecord()
            }else{
                self.recordButton.isSelected = false
                self.cameraUtils.stopRecord()
                
                //开始上传video
                SVProgressHUD.show()
                
                PKOSSUtils.upload(url: URL(string: self.cameraUtils.pathToMovie!)!, success: { (para, url) in
                    SVProgressHUD.dismiss()
                    //TODO:上传短视频url
                }, failure: { (error) in
                    SVProgressHUD.showError(withStatus: error?.localizedDescription)
                    SVProgressHUD.dismiss()
                })
            }
  
        }
        
        deleteButton.setImage(R.image.publish_shortVideo_delete(), for: .normal)
        deleteButton.addBlock(for: .touchUpInside) { (_) in
//            //TODO:删除
//            self.cameraUtils.stopRecord()
//            self.cameraUtils.isExist()
//            self.cameraUtils.play(From: self)
        }
        
        editButton.setImage(R.image.publish_shortVideo_edit(), for: .normal)
        editButton.addBlock(for: .touchUpInside) { (_) in
            //TODO:编辑
        }
        
        toggleButton.setImage(R.image.publish_shortVideo_toggle(), for: .normal)
        toggleButton.addBlock(for: .touchUpInside) { (_) in
            self.cameraUtils.toggle()
        }
        
        bottomContainerView.backgroundColor = UIColor.black
        
        selectionList.dataSource = self
        selectionList.delegate = self
        selectionList.centerButtons = true
        selectionList.centerOnSelection = true
        selectionList.setTitleColor(UIColor.white, for: .normal)
        selectionList.backgroundColor = UIColor.clear
        selectionList.selectionIndicatorColor = UIColor.blue
        
        secondsPicker.dataSource = self
        secondsPicker.delegate = self
        secondsPicker.backgroundColor = UIColor.clear
        
        recordButton.setImage(R.image.publish_shortVideo_record(), selectedImage: R.image.publish_shortVideo_stop()!)
    }
    
    override func setupSubViewsConstraints() {
        
        bottomContainerView.snp.makeConstraints { (make) in
            make.height.equalTo(200*D_FACTOR_Y)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.bottom.equalTo(view.snp.bottom)
        }
        
        previewView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        progressBarView.snp.makeConstraints { (make) in
            make.left.equalTo(previewView.snp.left)
            make.right.equalTo(previewView.snp.right)
            make.top.equalTo(previewView.snp.bottom)
            make.height.equalTo(3)
        }
        
        dismissButton.snp.makeConstraints { (make) in
            make.right.equalTo(view.snp.right).offset(-10)
            make.top.equalTo(view.snp.top).offset(10)
        }
        
        toggleButton.snp.makeConstraints { (make) in
            make.top.equalTo(dismissButton.snp.top)
            make.right.equalTo(dismissButton.snp.left).offset(-20)
        }
        
        editButton.snp.makeConstraints { (make) in
            make.top.equalTo(toggleButton.snp.top)
            make.right.equalTo(toggleButton.snp.left).offset(-20)
        }
        
        recordButton.snp.makeConstraints { (make) in
            make.center.equalTo(bottomContainerView.snp.center)
            make.width.equalTo(80)
            make.height.equalTo(80)
        }
        
        deleteButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(recordButton.snp.centerY)
            make.centerX.equalTo(bottomContainerView.snp.right).offset(-APP_WIDTH*0.25)
        }
        
        selectionList.snp.makeConstraints { (make) in
            make.top.equalTo(bottomContainerView.snp.top)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.height.equalTo(25)
        }
        
        cameraUtils.previewView!.snp.makeConstraints { (make) in
            make.edges.equalTo(previewView)
        }
        
        secondsPicker.snp.makeConstraints { (make) in
            make.centerY.equalTo(bottomContainerView.snp.centerY)
            make.centerX.equalTo(bottomContainerView.snp.left).offset(APP_WIDTH*0.25)
            make.width.equalTo(44)
        }
    }
    
    override func setupNavigationBar() {
        
    }
    
    override func bindViewModel() {
        
    }


}

extension PKPublishShortVideoController:HTHorizontalSelectionListDataSource,HTHorizontalSelectionListDelegate{
    
    func numberOfItems(in selectionList: HTHorizontalSelectionList) -> Int {
        return viewModel!.numberOfItemsForSelectionList()
    }
    
    func selectionList(_ selectionList: HTHorizontalSelectionList, titleForItemWith index: Int) -> String? {
        return viewModel!.titleForItemWith(index: index)
    }
    
    func selectionList(_ selectionList: HTHorizontalSelectionList, didSelectButtonWith index: Int) {
        
        //切换滤镜
        let title = viewModel?.titleForItemWith(index: index)
        cameraUtils.setFilter(filter: viewModel!.filterWith(title: title!))
        
        //切换selectionList
        selectionList.selectedButtonIndex = index
    }
}

extension PKPublishShortVideoController:UIPickerViewDataSource,UIPickerViewDelegate{
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return viewModel!.widthForComponent()
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return viewModel!.numberOfRowsInComponent()
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return viewModel!.rowHeightForComponent()
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return viewModel!.titleForRow(AtIndex: row)
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return viewModel!.numberOfComponents()
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        
        var pickerLabel = view as? UILabel
        if (view == nil){
            pickerLabel = UILabel()
            // Setup label properties - frame, font, colors etc
            //adjustsFontSizeToFitWidth property to YES
            pickerLabel?.adjustsFontSizeToFitWidth = true
            pickerLabel?.textAlignment = .left
            pickerLabel?.backgroundColor = UIColor.clear
            pickerLabel?.textColor = UIColor.blue
            pickerLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        }
        // Fill the label text here
        pickerLabel?.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
        
        return pickerLabel!
    }
    
    
    
}
